<template>
  <div class="history">
    <div class="top">
      <div class="left">
        <homeView></homeView>
      </div>
      <div class="right">
        <div class="title">报警记录</div>
        <div class="info">
          <div class="alarm-query">
            <el-date-picker
              v-model="alarmDate"
              type="datetimerange"
              value-format="YYYY-MM-DD HH:mm:ss"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
            <div class="query" @click="getAlarmFn()">查询</div>
          </div>
          <div class="table-box">
            <div class="table-h">
              <p>报警时间</p>
              <p>报警信息</p>
              <p style="white-space: nowrap">持续时间(分钟)</p>
            </div>
            <ul class="table-c">
              <li v-for="(item, index) in warningList" :key="item.start">
                <p>
                  <b class="num">{{ index + 1 }}</b>
                  {{ item.alarm_time }}
                </p>
                <p
                  :class="
                    stateName[item.state.batteryState]
                      ? stateName[item.state.batteryState].className
                      : ''
                  "
                >
                  {{ item.battery }}电池{{
                    stateName[item.state.batteryState]
                      ? stateName[item.state.batteryState].text
                      : ""
                  }}
                </p>
                <p>{{ item.alarm_duration }}</p>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
    <div class="bottom">
      <div class="title">历史趋势</div>
      <div class="info">
        <el-row :gutter="10">
          <el-col :span="3" class="xl-dc">
            <el-select
              placeholder="请选择电池"
              v-model="ele"
              clearable
              multiple
            >
              <el-option
                v-for="item in eleArr"
                :value="item.value"
                :label="item.name"
              ></el-option>
            </el-select>
          </el-col>
          <el-col :span="3">
            <el-select placeholder="温度和应变" v-model="yType" clearable>
              <el-option value="temperature" label="温度"></el-option>
              <el-option value="deformation" label="应变"></el-option>
              <el-option value="both" label="温度和应变"></el-option>
            </el-select>
          </el-col>
          <el-col :span="3">
            <el-select
              placeholder="请选择数据查询方式"
              v-model="types"
              clearable
            >
              <el-option
                v-for="item in typeList"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              ></el-option>
            </el-select>
          </el-col>
          <el-col :span="5" v-show="types == 1">
            <el-date-picker
              v-model="hisDate"
              type="datetimerange"
              value-format="YYYY-MM-DD HH:mm:ss"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 100%"
            ></el-date-picker>
          </el-col>
          <el-col :span="3" v-show="types == 2">
            <el-select
              placeholder="请选择查询时间段"
              v-model="times"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="item in timesList"
                :key="item"
                :value="item"
                :label="item"
              ></el-option>
            </el-select>
          </el-col>
          <el-col :span="3" v-show="types == 1">
            <div class="query" @click="getChartFn">查询</div>
          </el-col>
          <el-col :span="3" v-show="types == 2">
            <div class="query" @click="getChartFn2">查询</div>
          </el-col>
        </el-row>
        <div class="charts-box" ref="chartBox2"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import * as echarts from "echarts";
import homeView from "./HomeView.vue";

import useCounterStore from "../stores/counter.js";

const chartBox2 = ref(null);
let chartOne = undefined;

const eleArrs = useCounterStore().eleArr;
const stateNames = useCounterStore().batteryStatus;

let colorArr1 = [
  "#F9D50D",
  "#83EDF9",
  "#8550FF",
  "#FA8072",
  "#E53636",
  "#0D71FF",
  "#FD5825",
  "#0DBE00",
  "#DE3CF7",
  "#AB8D67",
  "#FD7CB1",
  "#FF9B0E",
  "#DEB887",
];
let colorArr2 = [
  "#F9D50D90",
  "#83EDF990",
  "#8550FF90",
  "#FA807290",
  "#E5363690",
  "#0D71FF90",
  "#FD582590",
  "#0DBE0090",
  "#DE3CF790",
  "#AB8D6790",
  "#FD7CB190",
  "#FF9B0E90",
  "#DEB88790",
];
let lineColor = {};
for (let i = 0; i < eleArrs.length; i++) {
  let item = eleArrs[i];
  let name = item.name;
  let after = parseInt(item.value.split("-")[1]) - 1;
  let color1 = colorArr1[after];
  let color2 = colorArr2[after];
  lineColor[name] = {};
  lineColor[name].color1 = color1;
  lineColor[name].color2 = color2;
}


const data = reactive({
  stateName: stateNames,
  warningList: [],
  alarmStartTime: undefined,
  alarmEndTime: undefined,
  alarmDate: undefined,
  eleArr: eleArrs,
  ele: undefined,
  yType: "temperature",
  types: undefined,
  typeList: [
    {
      id: 1,
      name: "自由查询",
    },
    {
      id: 2,
      name: "数据回放",
    },
  ],
  times: undefined,
  timesList: [],
  chaJson: {
    "0-25h": 15,
    "3h": 180,
    "6h": 360,
    "12h": 720,
  },
  hisDate: undefined,
  realData: {},
});
const {
  stateName,
  warningList,
  alarmStartTime,
  alarmEndTime,
  alarmDate,
  eleArr,
  ele,
  yType,
  types,
  typeList,
  hisDate,
  realData,
  times,
  timesList,
  chaJson,
} = toRefs(data);
import { listAlarm, getRecordChart, getHistoryChart, sjXl } from "../http/api.js";


shijianXl();

function shijianXl(){
  sjXl().then((res) => {
    timesList.value = res;
  })
}

initAlarm();
initChart();

// function queryTypesFn(){

// }

function getStartEndTime() {
  let curDate = new Date(hisDate.value).getTime();
  let start = getFormatTime(curDate - 1 * 60 * 1000);
  let end = getFormatTime(curDate + 1 * 60 * 1000);
  return {
    start: start,
    end: end,
  };
}

function getStartEndTime2() {
  let curDate = new Date().getTime();
  return {
    start: getFormatTime(curDate - chaJson.value[times.value] * 60 * 1000),
    end: getFormatTime(curDate),
  };
}

function getFormatTime(stamp) {
  // stamp = stamp * 1000;
  let year = new Date(stamp).getFullYear();
  let month = new Date(stamp).getMonth() + 1;
  month = month < 10 ? "0" + month : month;
  let date = new Date(stamp).getDate();
  date = date < 10 ? "0" + date : date;
  return (
    year +
    "-" +
    month +
    "-" +
    date +
    " " +
    new Date(stamp).toLocaleTimeString("chinese", { hour12: false })
  );
}

// 获取报警
function getAlarmFn() {
  alarmEndTime.value = alarmDate.value[1];
  alarmStartTime.value = alarmDate.value[0];
  listAlarm({
    start_time: alarmStartTime.value,
    stop_time: alarmEndTime.value,
  }).then((res) => {
    warningList.value = res;
  });
}
function initAlarm() {
  let now = getFormatTime(new Date().getTime());
  let year = now.split(" ")[0].split("-")[0];
  let month = now.split(" ")[0].split("-")[1];

  alarmEndTime.value = now;
  alarmStartTime.value = year + "-" + month + "-" + "01" + " 00:00:00";

  alarmDate.value = [alarmStartTime.value, alarmEndTime.value];
  getAlarmFn();
}

// 获取历史记录
function initChart() {
  types.value = 1;
  let monitorList = [];
  for (let i = 0; i < 3; i++) {
    monitorList.push(eleArr.value[i].value);
  }
  ele.value = monitorList;

  let end = getFormatTime(new Date().getTime());
  let start = getFormatTime(new Date().getTime() - 15 * 60 * 1000);
  hisDate.value = [start, end];
  getChartFn();
}
function getChartFn() {
  if (chartOne) {
    chartOne.clear();
    chartOne = null;
  }
  realData.value = {};
  let params = {
    start_time: hisDate.value[0],
    stop_time: hisDate.value[1],
    tag: yType.value,
  };

  callbackChart(params);
}
function _getChartFn2() {
  if (chartOne) {
    chartOne.clear();
    chartOne = null;
  }
  realData.value = {};
  if (!times.value) {
    times.value = "0-25h";
  }

  let sEtime = getStartEndTime2();
  let params = {
    start_time: sEtime.start,
    stop_time: sEtime.end,
    tag: yType.value,
  };

  callbackChart(params);
}

function getChartFn2() {
  if (chartOne) {
    chartOne.clear();
    chartOne = null;
  }

  _callbackChart();
}

function _callbackChart() {
  let queryStr = "";
  realData.value = {};
  for (let i = 0; i < ele.value.length; i++) {
    queryStr += "battery_name=" + ele.value[i] + "&";
  }
  getRecordChart({
    record_name: times.value
  }, queryStr).then((allRes) => {
    let _res = allRes;
    for (let j = 0; j < _res.length; j++) {
      let res = _res[j];
      for (let i = 0; i < res.length; i++) {
        let item = res[i];
        let key = item.battery;
        let serData = realData.value[key];
        if (!serData) {
          serData = {};
          serData.temperature = [];
          serData.deformation = [];
          realData.value[key] = serData;
        }
        if (yType.value == "both") {
          let value = res[i].temperature ? res[i].temperature.toFixed(2) : 0;
          let value2 = res[i].deformation ? res[i].deformation.toFixed(2) : 0;
          serData.temperature.push([new Date(res[i].time).getTime(), value]);
          serData.deformation.push([new Date(res[i].time).getTime(), value2]);
        } else {
          let value = res[i][yType.value] ? res[i][yType.value].toFixed(2) : 0;
          serData[yType.value].push([new Date(res[i].time).getTime(), value]);
        }
        // if (!minV.value) {
        //   minV.value = Number(value);
        // }
        // if (!maxV.value) {
        //   maxV.value = Number(value);
        // }
        // if (Number(value) < minV.value) {
        //   minV.value = Number(value);
        // }
        // if (Number(value) > maxV.value) {
        //   maxV.value = Number(value);
        // }
      }
    }
    drawChart();
  });
}


function callbackChart(params) {
  let queryStr = "";
  realData.value = {};
  for (let i = 0; i < ele.value.length; i++) {
    queryStr += "battery_name=" + ele.value[i] + "&";
  }
  getHistoryChart(params, queryStr).then((allRes) => {
    let _res = allRes;
    for (let j = 0; j < _res.length; j++) {
      let res = _res[j];
      for (let i = 0; i < res.length; i++) {
        let item = res[i];
        let key = item.battery;
        let serData = realData.value[key];
        if (!serData) {
          serData = {};
          serData.temperature = [];
          serData.deformation = [];
          realData.value[key] = serData;
        }
        if (yType.value == "both") {
          let value = res[i].temperature ? res[i].temperature.toFixed(2) : 0;
          let value2 = res[i].deformation ? res[i].deformation.toFixed(2) : 0;
          serData.temperature.push([new Date(res[i].time).getTime(), value]);
          serData.deformation.push([new Date(res[i].time).getTime(), value2]);
        } else {
          let value = res[i][yType.value] ? res[i][yType.value].toFixed(2) : 0;
          serData[yType.value].push([new Date(res[i].time).getTime(), value]);
        }
        // if (!minV.value) {
        //   minV.value = Number(value);
        // }
        // if (!maxV.value) {
        //   maxV.value = Number(value);
        // }
        // if (Number(value) < minV.value) {
        //   minV.value = Number(value);
        // }
        // if (Number(value) > maxV.value) {
        //   maxV.value = Number(value);
        // }
      }
    }
    drawChart();
  });
}
function drawChart() {
  if (!chartOne) {
    chartOne = echarts.init(chartBox2.value, "macarons");
  }
  let yData1 = []; // 温度
  let yData2 = []; // 应变
  let lineStyle1 = {
    // normal: {
    //   width: 2,
    // },
  };
  let lineStyle2 = {
    // normal: {
    //   width: 2,
    // },
    type: "dashed", // 设置为虚线
  };

  let yAxisArr = [];

  let wJson = {
    // max: 1500,
    // min: 400,
    name: "温度/℃",
    nameTextStyle: {
      color: "#dedede",
      padding: [0, 0, 15, 35], //表示[上,右,下,左]的边距
    },
    type: "value",
    splitLine: {
      lineStyle: {
        type: "dashed",
        color: "rgba(227,227,227,0.2)",
      },
    },
    axisLabel: {
      textStyle: {
        color: "#dedede",
      },
    },
    axisTick: {
      show: false,
    },
  };

  let yJson = {
    // max: 1500,
    // min: 400,
    name: "应变",
    nameTextStyle: {
      color: "#dedede",
      padding: [0, 0, 15, 35], //表示[上,右,下,左]的边距
    },
    type: "value",
    splitLine: {
      lineStyle: {
        type: "dashed",
        color: "rgba(227,227,227,0.2)",
      },
    },
    axisLabel: {
      textStyle: {
        color: "#dedede",
      },
    },
    axisTick: {
      show: false,
    },
  };

  if (yType.value == "temperature") {
    yAxisArr.push(wJson);
  } else if (yType.value == "deformation") {
    yAxisArr.push(yJson);
  } else if (yType.value == "both") {
    yAxisArr.push(wJson);
    yAxisArr.push(yJson);
  }
  if (yType.value == "both") {
    for (let key in realData.value) {
      // realData.value[key] = []; // 需要历史记录注释掉这一行
      let needLineStyle1 = JSON.parse(JSON.stringify(lineStyle1));
      needLineStyle1.color = lineColor[key].color1;
      let json1 = {
        name: key + "温度",
        type: "line",
        lineStyle: needLineStyle1,
        itemStyle: {
          color: lineColor[key].color1,
        },
        showSymbol: false,
        smooth: true,
        yAxisIndex: 0,
        data: realData.value[key]["temperature"],
      };
      let needLineStyle2 = JSON.parse(JSON.stringify(lineStyle2));
      needLineStyle2.color = lineColor[key].color2;
      let json2 = {
        name: key + "应变",
        type: "line",
        lineStyle: needLineStyle2,
        itemStyle: {
          color: lineColor[key].color2,
        },
        showSymbol: false,
        smooth: true,
        yAxisIndex: 1,
        data: realData.value[key]["deformation"],
      };

      yData1.push(json1);
      yData2.push(json2);
    }
  } else {
    for (let key in realData.value) {
      let needStyle =
        yType.value == "temperature"
          ? JSON.parse(JSON.stringify(lineStyle1))
          : JSON.parse(JSON.stringify(lineStyle2));
      needStyle.color =
        yType.value == "temperature"
          ? lineColor[key].color1
          : lineColor[key].color2;
      // realData.value[key] = []; // 需要历史记录注释掉这一行
      let json = {
        name: `${key}${yType.value == "temperature" ? "温度" : "应变"}`,
        type: "line",
        lineStyle: needStyle,
        itemStyle: {
          color:
            yType.value == "temperature"
              ? lineColor[key].color1
              : lineColor[key].color2,
        },
        showSymbol: false,
        smooth: true,
        data: realData.value[key][yType.value],
      };
      yData1.push(json);
    }
  }
  let option = {
    // color: ['#F9D50D', '#83EDF9', '#8550FF', '#2EFF8B', '#E53636', '#0D71FF', '#FD5825', '#0DBE00', '#DE3CF7', '#AB8D67', '#FD7CB1', '#FF9B0E', '#ffffff'],
    legend: {
      show: true,
      top: 0,
      textStyle: { color: "#ffffff" },
    },
    tooltip: {
      show: true,
      trigger: "axis",
      axisPointer: {
        // 坐标轴指示器，坐标轴触发有效
        type: "shadow", // 默认为直线，可选为：'line' | 'shadow'
      },
      axisPointer: {
        animation: false,
      },
      cofine: true,
    },
    grid: {
      top: 30,
      left: 30,
      right: 30,
      bottom: 0,
      containLabel: true,
    },
    xAxis: [
      {
        type: "time",
        // data: xData,
        axisLine: {
          show: false,
        },
        axisTick: {
          show: false,
        },
        axisLabel: {
          rotate: 0, // 将文字旋转 45 度
          padding: [0, 5, 0, 5], //文字左右定位
          textStyle: {
            color: "#dedede",
            fontSize: "14", //文字大小
          },
          formatter: (value, index) => {
            let dateTime = getFormatTime(value);
            return dateTime.split(" ")[1];
          },
        },
      },
    ],
    yAxis: yAxisArr,
    series: yData1.concat(yData2), // 需要历史记录放开这一行
    animationDuration: 0,
    animationEasing: "cubicInOut",
  };
  chartOne.setOption(option, true);
}
</script>

<style scoped lang="scss">
.history {
  width: 100%;
  height: 100%;
  pointer-events: auto;
  .top {
    height: 60%;
    display: flex;
    .left {
      width: 66%;
      height: 100%;
      position: relative;
    }
    .right {
      width: calc(34% - 0.8vw);
      height: 100%;
      margin-left: 0.8vw;
      background: url("../assets/img/realtime_right.png") center center
        no-repeat;
      background-size: 100% 100%;
      .title {
        color: #eaeffc;
        font-size: 1.5vh;
        padding-left: 1.6vh;
        letter-spacing: 0.6vh;
        height: 1.6vw;
        line-height: 1.7vw;
      }
      .info {
        height: calc(100% - 2.6vw);
        padding: 0 0.9vw;
        .alarm-query {
          margin-top: 0.6vw;
          display: flex;
          .query {
            width: 80px;
            height: 32px;
            text-align: center;
            line-height: 32px;
            background: url("../assets/img/query.png") center center no-repeat;
            background-size: 80px 32px;
            margin-left: 10px;
            color: #fff;
            cursor: pointer;
          }
        }

        .table-box {
          height: calc( 100% - 2.6vw );
          .table-h {
            height: 5vh;
            margin: 1vw 0 0.6vw 0;
            background-color: #041e55;
            p {
              display: inline-block;
              text-align: center;
              color: #a7a9af;
              line-height: 5vh;
              &:nth-child(1) {
                width: 38%;
              }
              &:nth-child(2) {
                width: 38%;
              }
              &:nth-child(3) {
                width: 24%;
              }
            }
          }
          .table-c {
            height: calc(100% - 7vh);
            overflow: auto;
            li {
              height: 4.5vh;
              margin-bottom: 0.6vw;
              background: #031644;
              p {
                display: inline-block;
                text-align: center;
                color: #fff;
                line-height: 4.5vh;
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
                &:nth-child(1) {
                  width: 38%;
                  position: relative;

                  .num {
                    display: block;
                    position: absolute;
                    width: 1.1vw;
                    height: 1.1vw;
                    left: 0.6vw;
                    top: 0.65vw;
                    background: url("../assets/img/num.png") center center
                      no-repeat;
                    background-size: 1.1vw 1.1vw;
                    text-align: center;
                    line-height: 1.1vw;
                    color: #f50e10;
                  }
                }
                &:nth-child(2) {
                  width: 38%;
                }
                &:nth-child(3) {
                  width: 24%;
                }
              }
            }
          }
        }
      }
    }
  }
  .bottom {
    height: calc(40% - 0.4vw);
    margin-top: 0.4vw;
    background: url("../assets/img/realtime_bottom.png") center center no-repeat;
    background-size: 100% 100%;
    .title {
      color: #eaeffc;
      font-size: 1.5vh;
      padding-left: 1.6vh;
      letter-spacing: 0.6vh;
      height: 1.9vw;
      line-height: 1.9vw;
    }
    .info {
      height: calc(100% - 1.9vw);
      padding: 0.9vw;
      .charts-box {
        height: calc(100% - 1.8vw);
        margin-top: 0.9vw;
      }
      .query {
        width: 80px;
        height: 32px;
        text-align: center;
        line-height: 32px;
        background: url("../assets/img/query.png") center center no-repeat;
        background-size: 80px 32px;
        color: #fff;
        cursor: pointer;
      }
    }
  }

  .table-c p.red {
    color: #ff1010 !important;
  }
  .table-c p.orange {
    color: #ff690e !important;
  }
  .table-c pp.purple {
    color: #8650ff !important;
  }
  .table-c p.yellow {
    color: #fad60d !important;
  }
  .table-c p.cyan {
    color: #bbffee !important;
  }
}
</style>
<style lang="scss">
.history .xl-dc {
  .el-select__selection.is-near {
    display: flex;
    flex-wrap: nowrap;
    overflow: hidden;
    width: 100%;
  }
}
.el-select-dropdown.is-multiple {
  .el-select-dropdown__wrap {
    width: 1150px;

    .el-select-dropdown__list {
      width: 100%;
      display: flex;
      flex-wrap: wrap;
    }
  }
}
</style>
